import { Menu } from '@/types';

/**
 * 工具函数封装
 */
export const formatMoney = (num?: number | string) => {
  if (!num) return 0.0;
  const a = parseFloat(num.toString());
  return a.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' });
};

export const formatNum = (num?: number | string) => {
  if (!num) return 0;
  const a = num.toString();
  if (a.indexOf('.') > -1) {
    return a.replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
  } else {
    return a.replace(/(\d)(?=(\d{3})+$)/g, '$1,');
  }
};

// 格式化日期
export const tolocalDate = (date?: Date, rule?: string) => {
  let curDate = new Date();
  if (date) curDate = date;
  if (rule === 'yyyy-MM-dd')
    return curDate.toLocaleDateString().replaceAll('/', '-');
  if (rule === 'HH:mm:ss')
    return curDate.toLocaleTimeString().replaceAll('/', '-');
  return curDate.toLocaleString().replaceAll('/', '-');
};

export const formatDate = (data?: Date | string, rule?: string) => {
  let curDate = new Date();
  if (data instanceof Date) curDate = data;
  else if (data) curDate = new Date(data);
  let fmt = rule || 'yyyy-MM-dd HH:mm:ss';
  type Otype = {
    [key: string]: number;
  };
  const O: Otype = {
    'y+': curDate.getFullYear(),
    'M+': curDate.getMonth() + 1,
    'd+': curDate.getDate(),
    'H+': curDate.getHours(),
    'm+': curDate.getMinutes(),
    's+': curDate.getSeconds()
  };
  for (const k in O) {
    fmt = fmt.replace(new RegExp(`(${k})`), O[k].toString().padStart(2, '0'));
  }
  return fmt;
};

export const formatState = (state: number) => {
  if (state === 1) return '在职';
  if (state === 2) return '试用期';
  if (state === 3) return '离职';
};

// 获取页面路径
export const getMenuPath = (list: Menu.MenuItem[]): string[] => {
  return list.reduce((result: string[], item: Menu.MenuItem) => {
    return result.concat(
      Array.isArray(item.children) && !item.buttons
        ? getMenuPath(item.children)
        : item.path + ''
    );
  }, []);
};

export const getTargetRouter: any = (path: string, routes: any[] = []) => {
  for (const item of routes) {
    if (item.path === path) return item;
    if (item.children) {
      const route = getTargetRouter(path, item.children);
      if (route) return route;
    }
  }
  return null;
};

// 手机号加密

export const encryptMobile = (mobile?: string | number) => {
  if (!mobile) return '';
  mobile = mobile.toString();
  const reg = new RegExp("(\\d{3})\\d*(\\d{4})",'g');
  return mobile.replaceAll(reg, "$1****$2")
}
